package com.dxy.elasticsearch.util;

import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @Description elasticsearch帮助器
 * @Author dangxianyue
 * @Date 2022/12/30 17:14
 */
@Slf4j
@Component
public class EsHelper {

    private final String logPrefix = "[Elasticsearch]->";

    @Autowired
    private RestHighLevelClient restHighLevelClient;

    /**
     * 创建索引
     *
     * @param index
     * @param jsonSource
     * @return
     */
    public boolean createIndex(String index, String jsonSource) {
        if (this.existIndex(index)) {
            log.warn("{}!!!试图创建已经存在的索引[{}]", logPrefix, index);
            return true;
        } else {
            try {
                CreateIndexRequest request = new CreateIndexRequest(index);
                request.source(jsonSource, XContentType.JSON);
                this.restHighLevelClient.indices().create(request, RequestOptions.DEFAULT);
                log.info("{}创建索引[{}]成功,jsonSource={}", logPrefix, index, jsonSource);
                return true;
            } catch (Exception var4) {
                log.info("{}创建索引[{}]失败,jsonSource={},失败原因:{}", logPrefix, index, jsonSource, var4.getMessage(), var4);
                return false;
            }
        }
    }

    /**
     * 删除索引
     *
     * @param index
     * @return
     */
    public boolean deleteIndex(String index) {
        if (!this.existIndex(index)) {
            log.warn("{}!!!试图删除不存在的索引[{}]", logPrefix, index);
            return true;
        } else {
            try {
                DeleteIndexRequest request = new DeleteIndexRequest(index);
                this.restHighLevelClient.indices().delete(request, RequestOptions.DEFAULT);
                log.info("{}删除索引[{}]成功", logPrefix, index);
                return true;
            } catch (Exception var3) {
                log.error("{}删除索引[{}]失败,原因:{}", logPrefix, index, var3.getMessage(), var3);
                return false;
            }
        }
    }

    /**
     * 索引是否存在
     *
     * @param index
     * @return
     */
    public boolean existIndex(String index) {
        try {
            GetIndexRequest request = new GetIndexRequest(index);
            return this.restHighLevelClient.indices().exists(request, RequestOptions.DEFAULT);
        } catch (Exception var3) {
            log.error("{}判断索引[{}]是否存在失败,原因:{}", logPrefix, index, var3.getMessage(), var3);
            return false;
        }
    }
}
